<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="main-nav">
          <div class="search-box">
            <a-input-search
              v-model:value="searchDriver"
              placeholder="搜索"
              :allowClear="true"
              @search="onSearchDriver"
            />
          </div>
          <BasicTree
            title=""
            ref="treeRef"
            :treeData="treeDataPro"
            :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
            :onSelect="handleTreeSelect"
            :actionList="actionList"
          />
        </div>
        <div class="main-content">
          <BasicTable @register="registerTable">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: '告警规则',
                      icon: 'ant-design:alert-outlined',
                      ifShow: hasPermission('8-4-4-lookRule'),
                      onClick: handleSetRule.bind(null, record),
                    },
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      ifShow: hasPermission('8-4-4-update'),
                      onClick: handleEdit.bind(null, record),
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      ifShow: hasPermission('8-4-4-del'),
                      onClick: handleDelete.bind(null, record),
                    },
                  ]"
                />
              </template>
            </template>
            <template #toolbar>
              <a-input-search
                v-model:value="searchValue"
                placeholder="请输入搜索的变量"
                style="width: 200px"
                :allowClear="true"
                @search="onSearch"
                v-if="curInfo.Type === 1"
              />
              <a-button
                type="primary"
                @click="handleAdd"
                v-if="curInfo.Type === 1 && hasPermission('8-4-4-add')"
              >
                新增
              </a-button>
              <a-button type="primary" @click="handleSave" v-if="hasPermission('8-4-4-save')">
                保存到配置文件
              </a-button>
            </template>
          </BasicTable>
        </div>
      </div>

      <!-- 表格 表单弹窗 -->
      <modelByDetail
        :info="detailForm"
        @register="registerByDetail"
        @submit-success="handleUpdateTable"
      />
      <!-- 分组弹窗 -->
      <modelByGroup
        :info="groupForm"
        @register="registerByGroup"
        @submit-success="handleUpdateTreeByGroup"
      />
      <!-- 告警规则抽屉 -->
      <drawerByElements @register="registerByElements" :info="detailForm" />
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { usePermission } from '/@/hooks/web/usePermission';
  import modelByDetail from '/@/views/project/alertRules/components/modelByDetail.vue';
  import modelByGroup from '/@/views/project/alertRules/components/modelByGroup.vue';
  import drawerByElements from '/@/views/project/alertRules/components/drawerByElements.vue';

  import { reactive, ref, unref, onMounted, onDeactivated, nextTick, h } from 'vue';
  import { BasicTree, TreeActionType, TreeActionItem } from '/@/components/Tree/index';

  import {
    getalarmtree,
    addgroup,
    editgroup,
    deletegroup,
    getalarmitem,
    saveconfig,
    addalarmitem,
    editalarmitem,
    deletealarmitem,
  } from '/@/api/alertRules/index';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
  const treeRef = ref<Nullable<TreeActionType>>(null);
  let curInfo = reactive({});
  let treeDataPro = ref([]);
  let searchValue = ref('');
  let searchDriver = ref('');
  const { hasPermission } = usePermission();
  const actionList: TreeActionItem[] = [
    /**
     * Type 0 服务 1 主机 2分组
     *
     */
    {
      show: (node) => {
        return [0].indexOf(node.Type) >= 0 && hasPermission('7-1-1-addGroup');
      },
      render: (node) => {
        return h(PlusOutlined, {
          class: 'ml-2',
          onClick: (e) => {
            e.stopPropagation();
            // if (node.Type === 0) {
            //   // 添加主机
            // } else {
            // 添加分组
            groupForm.type = 'add';
            groupForm.data = node;
            openModalByGroup(true, {});
            // }
          },
        });
      },
    },
    {
      show: (node) => {
        return [1, 2].indexOf(node.Type) >= 0 && hasPermission('7-1-1-updateGroup');
      },
      render: (node) => {
        return h(EditOutlined, {
          class: 'ml-2',
          onClick: async (e) => {
            e.stopPropagation();
            if (node.Type === 1) {
              loading.value = true;
              try {
                groupForm.type = 'update';
                groupForm.data = node;
                openModalByGroup(true, {});
                loading.value = false;
              } catch (error) {
                loading.value = false;
              }
            } else {
              groupForm.type = 'update';
              groupForm.data = node;
              openModalByGroup(true, {});
            }
          },
        });
      },
    },
    {
      show: (node) => {
        return [1, 2].indexOf(node.Type) >= 0 && hasPermission('7-1-1-delGroup');
      },
      render: (node: any) => {
        return h(DeleteOutlined, {
          class: 'ml-2',
          onClick: (e) => {
            e.stopPropagation();
            createConfirm({
              iconType: 'warning',
              okText: '确认',
              title: () => h('span', '温馨提示'),
              content: () => h('span', `是否确认删除该分组（${node.title}）`),
              onOk: async () => {
                try {
                  // node.Parentkey,
                  await deletegroup([node.title]);
                  createMessage.success(t('layout.setting.operatingTitle'));
                  initData();
                } catch (error) {}
              },
            });
          },
        });
      },
    },
  ];

  let groupForm = reactive({
    type: 'add',
    data: {},
    addgroup,
    editgroup,
  });

  let detailForm: any = reactive({
    type: 'add',
    data: {},
    addApi: addalarmitem,
    editApi: editalarmitem,
  });
  let isSearch = false;
  const loading = ref(false);
  const [
    registerByElements,
    { openDrawer: openDrawerByElements, closeDrawer: closeDrawerByElements },
  ] = useDrawer();
  const { createConfirm, createMessage } = useMessage();
  const { t } = useI18n();

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  let actionColumn = {
    width: 270,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };

  // 表单数据
  let columns: BasicColumn[] = [
    {
      title: '告警名称',
      dataIndex: 'Name',
    },
    {
      title: '关联变量',
      dataIndex: 'TagFullName',
      width: 400,
    },
    {
      title: '报警类别',
      dataIndex: 'AlarmType_text',
    },
    {
      title: '数据类型',
      dataIndex: 'DataTypeCn',
    },
    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];

  const [registerByGroup, { openModal: openModalByGroup, closeModal: closeModalByGroup }] =
    useModal();
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerTable, { reload, setTableData, getPaginationRef, setPagination }] = useTable({
    title: curInfo.title,
    api: getalarmitem,
    immediate: false,
    columns,
    pagination: true,
    actionColumn: hasPermission(['7-1-1-lookRule', '7-1-1-update', '7-1-1-del'])
      ? actionColumn
      : undefined,
    canResize: false,
    showIndexColumn: false,
    striped: true,
    bordered: true,
    fetchSetting: {
      pageField: 'PageNO',
      sizeField: 'PageSize',
      totalField: 'TotalRows',
      listField: 'Rows',
    },
    beforeFetch: () => {
      return [
        {
          SearchValue: isSearch ? searchValue.value : '',
          groupName: curInfo.title,
          PageNO: getPaginationRef().current || 1,
          PageSize: getPaginationRef().pageSize || 50,
        },
      ];
    },
    afterFetch: (v) => {
      let DataTypeObj = {
        3: '模拟量',
        4: '模拟量',
        5: '模拟量',
        6: '模拟量',
        7: '模拟量',
        8: '模拟量',
        1: '数字',
        11: '字符串',
      };
      return v.map((item) => {
        item.DataTypeCn = DataTypeObj[item.DataType];
        return item;
      });
    },
  });
  onMounted(async () => {
    try {
      initData(true);
    } catch (error) {}
  });
  onDeactivated(() => {
    closeDrawerByElements();
  });
  // 搜索方法
  function onSearch() {
    isSearch = ['', null, undefined].indexOf(searchValue.value) === -1;

    setPagination({
      current: 1,
    });
    reload();
  }
  // 搜索设备
  function onSearchDriver() {
    initData();
  }
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveconfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  async function handleUpdateTable() {
    closeModalByDetail();
    setTimeout(() => {
      reload();
    }, 250);
  }
  function handleUpdateTreeByGroup() {
    closeModalByGroup();
    initData();
  }
  function eachTree(treeDatas: any[]) {
    treeDatas.forEach((element) => {
      element.title = element.Name;
      // switch (element.Type) {
      //   case 0:
      //     element.icon = 'ant-design:home-outlined';
      //     break;
      //   case 1:
      //     element.icon = 'ant-design:database-outlined';
      //     break;
      //   case 2:
      //     element.icon = 'ant-design:bars-outlined';
      //     break;
      //   case 3:
      //     element.icon = 'ant-design:folder-outlined';
      //     break;
      //   default:
      //     break;
      // }

      if (element.Children) eachTree(element.Children);
    });
  }
  async function initData(isOpenTree = false) {
    loading.value = true;
    try {
      let resByTree = await getalarmtree(searchDriver.value ? [searchDriver.value] : [null]);
      eachTree(resByTree);
      treeDataPro.value = resByTree || [];
      if (isOpenTree) {
        nextTick(() => {
          getTree().filterByLevel(1);
        });
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = { serverName: curInfo.title };
    openModalByDetail();
  }
  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '温馨提示'),
      content: () => h('span', `是否确认删除该告警（${record.Name}）`),
      onOk: async () => {
        try {
          await deletealarmitem([curInfo.title, `${record.Name}`]);
          createMessage.success(t('layout.setting.operatingTitle'));
          reload();
        } catch (error) {}
      },
    });
  }
  function handleEdit(record: Recordable) {
    detailForm.type = 'update';
    detailForm.data = { serverName: curInfo.title, ...record };
    openModalByDetail();
  }
  function handleSetRule(record: Recordable) {
    console.log('点击了告警规则', record);
    detailForm.type = 'elements';
    detailForm.data = record;
    openDrawerByElements();
  }
  function handleTreeSelect(_e, info) {
    searchValue.value = '';
    if (info.node?.Type === 1) {
      curInfo = info.node;
      reload();
    } else {
      setTableData([]);
      curInfo = {};
    }
  }
</script>
<script lang="ts">
  export default {
    name: 'AlertRulesIndex',
  };
</script>
<style scoped lang="less">
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
  }

  .tag {
    position: relative;
    overflow: hidden;
    height: 100%;
    background-color: #fff;

    .main-nav {
      position: absolute;
      top: 0;
      left: 0;
      width: 240px;
      height: 100%;
      padding: 8px;
      box-sizing: border-box;
      overflow: auto;
      background-color: rgba(8, 30, 66, 0.04);
      border-radius: 3px;

      .tree-style {
        position: absolute;
        top: 0;
        left: 0;
        padding: 8px;
        width: 240px;
        z-index: 2;
        bottom: 0;
        box-sizing: border-box;
      }
    }

    .main-content {
      position: relative;
      height: 100%;
      margin-left: 260px;
      overflow: hidden;
    }
  }

  .add-server {
    width: 100%;
    position: relative;
    z-index: 5;
    margin-bottom: 10px;
  }
</style>
